<template>
  <div>
    <card :showDivider="false" :title="`${!id ? '新增' : '编辑'}围栏`" labelTooltipContent="新增围栏，默认创建围栏预警" />
    <a-spin :loading="loading" style="width: 100%">
      <page-form :model="form" layout="vertical" ref="formRef" :rules="formRules">
        <page-form-row>
          <page-form-item field="fenceName" label="围栏名称" required>
            <i-input placeholder="请输入" v-model="form.fenceName" :max-length="20" />
          </page-form-item>
          <page-form-item field="electricRemark" label="围栏说明">
            <i-input placeholder="请输入" v-model="form.electricRemark" :max-length="50" />
          </page-form-item>
          <page-form-item field="rule" label="围栏规则" required>
            <a-select placeholder="请选择" v-model="form.rule" allow-clear>
              <a-option v-for="item in fenceDict.vehiceFenceRuleEnum" :key="item.value" :label="item.label" :value="item.value" />
            </a-select>
          </page-form-item>
          <page-form-item field="siteList" label="应用门店" required>
            <remote-select
              v-model="form.siteList"
              type="multiple_site_lease_list"
              @change="changeSelect"
              @optionsList="siteListChangData"
            />
          </page-form-item>
          <page-form-item field="carInfoList" label="应用车辆" required>
            <remote-select
              v-model="form.carInfoList"
              v-model:allValue="form.selectAllCarFlag"
              :mustParentShow="!form.siteList || form.siteList.length == 0"
              all-show
              :params="{
                siteIdList: form.siteList,
                operateStatusList: [10, 20, 30],
              }"
              :disabled="!form.siteList || form.siteList.length == 0"
              mustParentTip="请选择"
              all-label="全部车辆"
              type="multiple_car_licensenno_list"
              @optionsList="carListChangData"
            />
          </page-form-item>
          <page-form-item field="status" label="围栏状态" required>
            <a-select placeholder="请选择" v-model="form.status" allow-clear>
              <a-option v-for="item in fenceDict.vehiceFenceStatusEnum" :key="item.value" :label="item.label" :value="item.value" />
            </a-select>
          </page-form-item>
          <page-form-item class="form-item" field="electricFenceList" label="围栏范围" required>
            <a-button type="primary" @click="emit('editFence')">编辑围栏</a-button>
            <div class="fence-type-list" v-if="fenceText"> {{ fenceText }} </div>
            <a-input style="display: none" v-model="form.electricFenceList" />
          </page-form-item>
          <page-form-item size="1" v-if="form.rule">
            <section>
              <div class="flex">
                <span class="title">{{ form.rule == '1' ? '禁出' : '禁入' }}围栏告警</span>
                <a-switch :checked-value="1" :unchecked-value="0" class="switch" v-model="form.needWarning" />
                <a-tooltip>
                  <template #content> 关闭后，车辆{{ form.rule == '1' ? '驶出禁出' : '驶入禁入' }}区域不再进行告警 </template>
                  <icon-question-circle style="font-size: 20px; color: #ff7d00" />
                </a-tooltip>
              </div>
              <div class="block w-full">
                处于租赁中的车辆绑定的GPS上报位置连续
                <i-input-number
                  v-model="form.rentWarningMinus"
                  :min="0"
                  :max="720"
                  :default-value="2"
                  :allow-clear="false"
                  :precision="0"
                  :style="{ width: '150px' }"
                  unit="分钟"
                />都在{{ form.rule == '1' ? '禁出围栏外' : '禁入围栏内' }}，触发预警提醒。
              </div>
              <div class="block w-full">
                处于运维中和空闲可租的车辆绑定的GPS上报位置连续
                <i-input-number
                  v-model="form.otherWarningMinus"
                  :min="0"
                  :max="720"
                  :default-value="10"
                  :allow-clear="false"
                  :precision="0"
                  :style="{ width: '150px' }"
                  unit="分钟"
                />都在{{ form.rule == '1' ? '禁出围栏外' : '禁入围栏内' }}，触发预警提醒。
              </div>
            </section>
          </page-form-item>
        </page-form-row>
      </page-form>
    </a-spin>

    <page-form-footer :ok-loading="loading" @ok="saveCarModel" />
  </div>
</template>
<script setup>
  import { ref, computed, inject } from 'vue'
  import { usePageDict } from '@/hooks/useDict'
  import { addVehiceFence, updateVehiceFence } from '@/api/business/fence'
  import { formRules } from '../options'
  import useNavigate from '@/hooks/useNavigate'

  const { navigateBack } = useNavigate()
  const props = defineProps({
    id: String,
    loading: {
      type: Boolean,
      default: true,
    },
  })

  const emit = defineEmits(['editFence']) // 返回
  const fenceDict = usePageDict('fenceDict') // 门店和车辆列表
  const form = inject('form') // 围栏数据

  // eslint-disable-next-line vue/return-in-computed-property
  const fenceText = computed(() => {
    // 过滤数据
    if (form.electricFenceList && form.electricFenceList.length > 0) {
      const fenceTypeList = form.electricFenceList.map((val) => {
        return val.name
      })
      return fenceTypeList.join('|')
    }
  })

  //清空关联数据
  const changeSelect = () => {
    form.carInfoList = []
  }
  // 获取门店
  const siteDataList = ref(null)
  // 获取门店数据
  const siteListChangData = (data) => {
    siteDataList.value = data
  }

  // 获取车辆数据
  const carDataList = ref(null)
  const carListChangData = (data) => {
    carDataList.value = data
    // // 清除对应门店的数据
    // if (form.carInfoList && data) {
    //   const result = data.filter((obj) => form.carInfoList.includes(obj.id + ''))
    //   form.carInfoList.length = 0
    //   form.carInfoList = result.map((obj) => {
    //     return obj.id + ''
    //   })
    // }
  }

  // 筛选门店集合
  const screenSiteList = () => {
    const options = siteDataList.value
      .map(({ id, siteName }) => {
        if (form.siteList.includes(id + '')) {
          return {
            siteName,
            siteId: id,
          }
        }
      })
      .filter((item) => item !== null && item !== undefined)
    form.siteListData = options
  }
  // 筛选车辆集合
  const screenCarInfoList = () => {
    const options = carDataList.value
      .map(({ id, vin, licenseNo }) => {
        if (form.carInfoList.includes(id + '')) {
          return {
            carId: id,
            vin,
            licenseNo,
          }
        }
      })
      .filter((item) => item !== null && item !== undefined)
    return options
  }

  // 处理data
  const paramsData = () => {
    let formData = { ...form }
    screenSiteList()

    // 判断是否是全部
    if (formData.carInfoList == 'all') {
      formData.carInfoList = null
    } else {
      formData.carInfoList = screenCarInfoList()
    }
    // 处理数据
    // console.log(3333, formData.selectAllCarFlag)
    formData.selectAllCarFlag = formData.selectAllCarFlag ? 1 : 0
    formData.siteList = form.siteListData
    delete formData.siteListData
    delete formData.changeCarInfoList
    return formData
  }

  //  保存
  const formRef = ref(null)
  const saveCarModel = (noticeSuccess) => {
    formRef.value.validate(async (error) => {
      if (error) {
        console.log(error)
      } else {
        const formData = paramsData()
        console.log('----form', formData)
        const res = !props.id ? await addVehiceFence(formData) : await updateVehiceFence(formData)
        if (res.code == 200) {
          navigateBack()
          // 成功提示
          noticeSuccess()
        }
      }
    })
  }
</script>
<style lang="less" scoped>
  .form-item {
    :deep(.arco-form-item-content-flex) {
      display: inline-table;
    }
  }

  .fence-type-list {
    width: max-content;
    margin-top: 10px;
    padding: 20px;
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    background: rgba(247, 248, 250, 0.5);
    font-weight: 400;
    color: #1d2129;
    line-height: 22px;
  }
  .flex {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }
  .title {
    font-size: 14px;
    font-weight: bold;
  }
  .switch {
    margin: 0 5px 0 35px;
  }
  .w-full {
    margin-bottom: 20px;
  }
</style>
